#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file: phone_info.py
@time: 2024-07-14 15:36
@desc:
文档详情
https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
"""
import traceback

import requests
import json
from common_tools import to_dict
from global_scope import get_wechat_access_token


def get_phone_number(code, logger, trace_logger):
    try:
        logger.info("wechat get phone number requests prepare")
        url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
        payload = {
            "code": code
        }
        headers = {
            "Content-Type": "application/json"
        }
        response = requests.post(
            url, data=json.dumps(payload), headers=headers,
            params=to_dict(
                access_token=get_wechat_access_token())
        )
        logger.info("wechat get phone number requests start")
        if 200 <= response.status_code < 300:
            logger.info("wechat get phone number requests success")
            data = response.json()
            return (
                data["phone_info"]["purePhoneNumber"],
                data["phone_info"]["countryCode"],
                data["phone_info"]["phoneNumber"],
                json.dumps(data["phone_info"], ensure_ascii=False))
        else:
            logger.info(f"wechat get phone number requests failed:{response.status_code}")
            logger.info(f"wechat get phone number requests failed:{response.content}")
            return
    except Exception as e:
        logger.info(f"wechat get phone number requests error: {e}")
        t = traceback.format_exc()
        trace_logger.error(f"Wechat Access Token Request Error:{e}\n{t}")
    finally:
        logger.info("wechat get phone number requests finished")


def demo():
    # 示例使用
    access_token = "你的access_token"
    code = "你的code"
    import logging
    logger = logging.getLogger("wechat")
    phone_number_info = get_phone_number(code, logger, logger)
    print(phone_number_info)